package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Client;
import org.ahuanlien.crm.mapper.ClientMapper;
import org.ahuanlien.crm.query.ClientQueryObject;
import org.ahuanlien.crm.query.QueryObject;
import org.ahuanlien.crm.service.IClientService;
import org.ahuanlien.crm.util.PageResult;
import org.ahuanlien.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ClientServiceImpl implements IClientService {

	@Autowired
	private ClientMapper clientMapper;

	public PageResult query(QueryObject qo) {
		int count = clientMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Client> result = clientMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public void saveOrUpdate(Client record) {
		if (record.getId() != null) {
			clientMapper.updateByPrimaryKey(record);
		} else {
			record.setCreateEmp(UserContext.getCurrentUser().getUsername());
			record.setCreateDate(new Date());
			clientMapper.insert(record);
		}
	}

	public void moveResource(Long clientId) {
		clientMapper.ChangeState(clientId,1);
	}

	public PageResult querySrouce(ClientQueryObject qo) {
		int count = clientMapper.queryForCountResource(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Client> result = clientMapper.queryForListResource(qo);
		return new PageResult(count, result);
	}

	public void absorbClient(Long clientId) {
		clientMapper.updateChargeEmp(clientId,UserContext.getCurrentUser().getUsername());
		clientMapper.ChangeState(clientId,0);
	}

	public Client selectByPrimaryKey(Long id) {
		return clientMapper.selectByPrimaryKey(id);
	}
}
